<?php
namespace Framework;



class Application extends Module 
{

    public $controllerNamespace = 'App\\Controllers';

    public $name = 'My Application';

    public $_request;

    public $app = [];

    public $module = [
        'admin' => [
            'class' => 'App\Admin\Module',
        ]
    ];

	function __construct($basePath = null, $components = []){

		App::$base = $this;

        //注册组件
        $this->_components = $this->regComponents($components);

        //Facade门面命名空间简化
        // spl_autoload_register([$this, 'load']);

		//错误处理注册
		(new Error())->register();



        require __DIR__ . '/helpers.php';


        //设置目录别名
        alias('@base', $basePath);
        alias('@app', '@base/src');
        alias('@config', '@base/config');
        alias('@runtime', '@base/runtime');
        alias('@templates', '@base/templates');

	}


    public function coreComponents()
    {
        return [
            'request'      => ['_class' => Http\Request::class],
            'response'     => ['_class' => Http\Response::class],
            'db'           => ['_class' => Database\Db::class],
            'cache'        => ['_class' => Cache\Cache::class],
            'config'       => ['_class' => Config::class],
            'view'         => ['_class' => View\View::class],
            'log'          => ['_class' => Log\Logger::class],
        ];
    }

    public function load($alias_name)
    {
        // $alias = [
        //     'Config' => "\Framework\Facades\Config",
        //     'Request' => "\Framework\Facades\Request",
        // ];  
        // if( isset($alias[$alias_name]) ){
        //     return class_alias($alias[$alias_name], $alias_name);

        // }

        $className = "\Framework\Facades\\$alias_name";
        if( class_exists($className) ){
            return class_alias($className, $alias_name);
        }
    }

    public function handleRequest()
    {
        // 从Url中拆分出路由和参数
        $route = $this->request->path();
        $params = [];
        $result = $this->runAction($route, $params);


        //如果响应的就是response对象
        if ($result instanceof Http\Response) {
            return $result;
        }

        //响应
        $response = $this->response;
        if ($result !== null) {
            $response->data = $result;
        }

        return $response;
    }



	public function run(){
        return $this->handleRequest();
		//先判断要访问的action 通过注释路由、映射路由
		list($controller, $action) = $this->getActionByUrlMappings();

		//运行具体的控制器 
		$result = $this->runMiddleware($controller, $action);

		
		if( $result != null && is_array($result) ){
            $this->response->json($result);

		}else{
            $this->response->data = $result;
        }

		return $this->response;
	}

	public function runMiddleware($controller, $action){


		if( !class_exists($controller) ){
			$controller = '\\'.$controller;
		}

		$_class = new $controller();
		$this->app = [$_class, $action];

		if( method_exists($_class, $action) ){

			//执行中间件
			$middleware = new Middleware();

			//注册中间件
			// $middleware->register(\App\Middleware\Testt::class);
			$middleware->register(\App\Middleware\Test::class);


			$run = $middleware->middleware(function(){
				return $this->runAction();
			});

			return $run();
			
		}else{
			throw new \Exception("方法 {$action} 不存在, 在 {$controller}");
		}
	}

	

}